<template>
	<view>
		<nav-ber :title="'签名'" :bgColor="'#f7f8ff'"></nav-ber>
		<view class="index">
		  <!-- 样例1 -->
		  <view class="container1" id="aaa" v-if="!fullScreen">
		    <canvas
		      type="2d"
		      id="signature1"
		      class="signature1"
		      :style="'width:'+width1+'px;height:'+height1+'px'"
		      :disable-scroll="true"
		      bindtouchstart="handleTouchStart1"
		      bindtouchmove="handleTouchMove1"
		      bindtouchcancel="handleTouchEnd1"
		      bindtouchend="handleTouchEnd1"
		    ></canvas>
		    <view class="actions1">
		      <button bindtap="handleClear1" >
		        清除
		      </button>
		      <button bindtap="handleUndo1">
		        返回上一次描绘
		      </button>
		      <view @click="handlePreview1">查看图片</view>
		      <!-- <button bindtap="handleColor1">
		        Change Color
		      </button>
		      <button bindtap="handleFullScreen1">
		        Full Screen
		      </button> -->
		    </view>
		  </view>
		  <!-- 样例2（伪全屏） -->
		  <view class="container2" v-if="fullScreen">
		    <view class="actions2Wrap">
		      <view class="actions2">
		        <button bindtap="handleClear2">
		          Clear
		        </button>
		        <button bindtap="handleUndo2">
		          Undo
		        </button>
		        <button bindtap="handlePreview2">
		          View PNG
		        </button>
		        <button bindtap="handleColor2">
		          Change Color
		        </button>
		        <button bindtap="handleFullScreen2">
		          Close Full Screen
		        </button>
		      </view>
		    </view>
		    <canvas
		      type="2d"
		      id="signature2"
		      class="signature2"
		      :style='"width:"+width2+"px;height:"+height2+"px;"'
		      :disable-scroll="true"
		      bindtouchstart="handleTouchStart2"
		      bindtouchmove="handleTouchMove2"
		      bindtouchcancel="handleTouchEnd2"
		      bindtouchend="handleTouchEnd2"
		    ></canvas>
		    <!-- 伪全屏生成旋转图片canvas容器，不在页面上展示 -->
		    <view style="position:fixed;left:-2000px;width:0;height:0;overflow:hidden">
		      <canvas
		        canvas-id="signature3"
		        :style='"width:"+height2+"px;height:"+height2+"px;"'
		      />
		    </view>
		  </view>
		</view>

	</view>
</template>

<script>
	import Signature from './sign.js';
	export default {
	  data() {
			return {
				fullScreen: false,
				width1: 320,
				height1: 200,
				width2: 320,
				height2: 600,
				scale: 2,
				signature1: null,
				type: 0
			}
	  },
		onReady() {
			try {
				const { windowWidth, windowHeight, pixelRatio  } = uni.getSystemInfoSync();
				this.setData({
					width1: windowWidth - 30,
					height1: 200,
					width2: windowWidth - 80,
					height2: windowHeight - 50,
					scale: Math.max(pixelRatio || 1, 2),
				})
			} catch (e) { }
			if (this.fullScreen) {
				this.initSignature2();
			} else {
				this.initSignature1();
			}
		},
		onLoad(option) {

			this.type = option.type

		},
		methods: {
			// 样例1初始化
			  initSignature1() {
					// const query = uni.createSelectorQuery().in(this);
					// query.select('#aaa').boundingClientRect(data => {
					// 	console.log('data4235', data)
					// }).exec();
					 // let doms=uni.createSelectorQuery().selectAll('#signature1')
					 // 		doms.fields({
					 // 			node:true,   //是否返回节点布局位置信息{left,top,right,bottom}
					 // 			size:true,  //是否返回节点尺寸信息{width，height}
					 // 			scrollOffset:true //是否返回节点滚动信息{scrollLeft,scrollTop}
					 // 		},function(res){
					 // 			//res 可以返回第一个参数对象中指定为true的相关信息
						// 		console.log('fasdg', res)
					 // 		}).exec(function(){
					 // 			//上述节点信息获取成功后执行的回调函数
					 // 		})
					// computed:{
					// 	// 设置谚语的位置
					// 	heightSet: function(){
					// 		return this.f_info.height-20;
					// 	}
					// },
			    uni.createSelectorQuery().select('#signature1').fields({ node: true, size: true }).exec((res) => {
						console.log('res124', res)
			      const canvas = res[0].node;
			      canvas.width = this.width1 * this.scale;
			      canvas.height = this.height1 * this.scale;
			      const ctx = canvas.getContext('2d');
			      this.signature1 = new Signature(ctx, {
			        width: this.width1,
			        height: this.height1,
			        scale: this.scale,
			        bgColor: '#fff', //画布背景
			        toDataURL: (type, quality) => canvas.toDataURL(type, quality),
			        requestAnimationFrame: (fn) => canvas.requestAnimationFrame(fn),
			        getImagePath: () => new Promise((resolve, reject) => {
			          const img = canvas.createImage();
			          img.onerror = reject;
			          img.onload = () => resolve(img);
			          img.src = canvas.toDataURL();
			        })
			      })
			    })
			  },
			
			  // 样例2初始化（伪全屏）
			  initSignature2() {
			    uni.createSelectorQuery().select('#signature2').fields({ node: true, size: true }).exec((res) => {
			      const canvas = res[0].node;
			      this.canvas2 = canvas;
			      canvas.width = this.width2 * this.scale;
			      canvas.height = this.height2 * this.scale;
			      const ctx = canvas.getContext('2d');
			      this.signature2 = new Signature(ctx, {
			        width: this.width2,
			        height: this.height2,
			        scale: this.scale,
			        minWidth: 4,
			        maxWidth: 10,
			        bgColor: '#e9cb93',
			        toDataURL: (type, quality) => canvas.toDataURL(type, quality),
			        requestAnimationFrame: (fn) => canvas.requestAnimationFrame(fn),
			        getImagePath: () => new Promise((resolve, reject) => {
			          const img = canvas.createImage();
			          img.onerror = reject;
			          img.onload = () => resolve(img);
			          img.src = canvas.toDataURL();
			        })
			      })
			    })
			  },
			
			  /**
			   * 样例1事件绑定
			   */
			  handleTouchStart1(e) {
			    const pos = e.touches[0];
			    this.signature1.onDrawStart(pos.x, pos.y);
			  },
			  handleTouchMove1(e) {
			    const pos = e.touches[0];
			    this.signature1.onDrawMove(pos.x, pos.y);
			  },
			  handleTouchEnd1() {
			    this.signature1.onDrawEnd();
			  },
			
			  /**
			   * 样例2事件绑定
			   */
			  handleTouchStart2(e) {
			    const pos = e.touches[0];
			    this.signature2.onDrawStart(pos.x, pos.y);
			  },
			  handleTouchMove2(e) {
			    const pos = e.touches[0];
			    this.signature2.onDrawMove(pos.x, pos.y);
			  },
			  handleTouchEnd2() {
			    this.signature2.onDrawEnd();
			  },
			
			  /**
			   * 样例1按钮事件
			   */
			  handleFullScreen1() {
			    this.setData({ fullScreen: true })
			    setTimeout(() => this.initSignature2(), 50)
			  },
			  handleClear1() {
			    this.signature1.clear();
			  },
			  handleUndo1() {
			    this.signature1.undo();
			  },
			  handleColor1() {
			    this.signature1.color = '#' + Math.random().toString(16).slice(-6);
			  },
			  handlePreview1() {
					let arr;
					if (uni.getStorageSync('singImg')) {
						arr = JSON.parse(uni.getStorageSync('singImg'))
					} else {
						arr = []
					}
					arr[this.type] = {
						type: this.type == 0? 0 : (this.type == 1? 2 : 3),
						url: 'https://cdn.uviewui.com/uview/album/1.jpg'
					}
					uni.setStorage({
						key: 'singImg',
						data: JSON.stringify(arr)
					})
					uni.navigateBack({
						delta: 1,
					})
			    // if (this.signature1.isEmpty()) {
			    //   uni.showToast({ icon: 'none', title: '未签名' });
			    //   return;
			    // }
			    // const dataURL = this.signature1.toDataURL();
			    // console.log(dataURL)
			    // this.base64ToPath(dataURL).then(url => {
			    //     console.log(url)
			    //   url && uni.previewImage({
			    //     current: 0,
			    //     urls: [url],
			    //   });
			    // });
			  },
				
			  /**
			   * 样例2按钮事件
			   */
			  handleFullScreen2() {
			    this.setData({ fullScreen: false })
			    setTimeout(() =>  this.initSignature1(), 50)
			  },
			  handleClear2() {
			    this.signature2.clear();
			  },
			  handleUndo2() {
			    this.signature2.undo();
			  },
			  handleColor2() {
			    this.signature2.color = '#' + Math.random().toString(16).slice(-6);
			  },
			  handlePreview2() {
			    if (this.signature2.isEmpty()) {
			      uni.showToast({ icon: 'none', title: '未签名' });
			      return;
			    }
			    this.getRotateImage().then(url => {
			      url && uni.previewImage({
			        current: 0,
			        urls: [url],
			      });
			    });
			  },
			
			   // 样例2伪全屏输出旋转图片
			   async getRotateImage() {
			    const dataURL = this.signature2.toDataURL();
			    const url = await this.base64ToPath(dataURL);
			    const ctx = uni.createCanvasContext('signature3');
			    const width = this.signature2.width;
			    const height = this.signature2.height;
			    ctx.restore();
			    ctx.save();
			    ctx.translate(0, height);
			    ctx.rotate(270 * Math.PI / 180);
			    ctx.drawImage(url, 0, 0, width, height);
			    ctx.draw();
			    return new Promise((resolve, reject) => {
			      setTimeout(() => {
			        uni.canvasToTempFilePath({
			          canvasId: 'signature3',
			          x: 0,
			          y: height - width,
			          width: height,
			          height: width,
			          success: res => resolve(res.tempFilePath),
			          fail: reject,
			        })
			      }, 50)
			    })
			  },
				base64ToPath(dataURL) {
				  return new Promise((resolve, reject) => {
				    const data = uni.base64ToArrayBuffer(dataURL.replace(/^data:image\/\w+;base64,/, ""));
				    const filePath = `${uni.env.USER_DATA_PATH}/${Math.random().toString(32).slice(2)}.png`;
				    uni.getFileSystemManager().writeFile({
				      filePath,
				      data,
				      encoding: 'base64',
				      success: () => resolve(filePath),
				      fail: reject,
				    });
				  })
				}
			}
	}
</script>

<style>
</style>